package cn.chuengxu;

import cn.chuengxu.utils.ESClientUtil;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;

import javax.naming.Name;
import java.util.HashMap;
import java.util.Map;

public class EsTest {

    /**======================================================================================
    * @Title: testAdd
    * @Description: ElasticSearch简单模式-添加文档
    * @Author: Mr.Zhang
    * @Version: 1.0
    * @Date:  2022/7/24 18:30
    * @Parameters: []
    * @Return void
    ======================================================================================*/
    @Test
    public void testAdd() throws Exception {

        // 获取连接对象
        TransportClient client = ESClientUtil.getClient();
        // 设置要添加的数据
        Map<String, Object> map = new HashMap<>();
        map.put("id",1);
        map.put("name","张三");
        map.put("age",3);
        map.put("sex",1);

        // 调用连接的对象进行添加
        IndexRequestBuilder indexRequestBuilder = client.prepareIndex("pethome", "pet", "1").setSource(map);
        System.out.println(indexRequestBuilder.get());

        // 关流
        client.close();
    }

    /**======================================================================================
    * @Title: testLoad
    * @Description: ElasticSearch简单模式-查问文档
    * @Author: Mr.Zhang
    * @Version: 1.0
    * @Date:  2022/7/24 18:39
    * @Parameters: []
    * @Return void
    ======================================================================================*/
    @Test
    public void testLoad() throws Exception {

        // 获取连接对象
        TransportClient client = ESClientUtil.getClient();

        // 进行查询
        Map<String, Object> source = client.prepareGet("pethome", "user", "14").get().getSource();

        // 打印
        System.out.println(source);

        // 关流
        client.close();
    }

    /**======================================================================================
    * @Title: testUpt
    * @Description: ElasticSearch简单模式-修改文档
    * @Author: Mr.Zhang
    * @Version: 1.0
    * @Date:  2022/7/24 18:42
    * @Parameters: []
    * @Return void
    ======================================================================================*/
    @Test
    public void testUpt() throws Exception {

        // 获取连接对象
        TransportClient client = ESClientUtil.getClient();

        Map<String, Object> map = new HashMap<>();
        map.put("name","二愣子");

        // 进行修改
        UpdateResponse updateResponse = client.prepareUpdate("pethome", "pet", "1").setDoc(map).get();

        // 打印
        System.out.println(updateResponse);

        // 关流
        client.close();
    }

    /**======================================================================================
    * @Title: testdel
    * @Description: ElasticSearch简单模式-删除文档
    * @Author: Mr.Zhang
    * @Version: 1.0
    * @Date:  2022/7/24 18:47
    * @Parameters: []
    * @Return void
    ======================================================================================*/
    @Test
    public void testdel() throws Exception {

        // 获取连接对象
        TransportClient client = ESClientUtil.getClient();


        // 进行删除
        DeleteResponse deleteResponse = client.prepareDelete("pethome", "pet", "1").get();

        // 打印
        System.out.println(deleteResponse);

        // 关流
        client.close();
    }

    /**======================================================================================
    * @Title: testComplexQuery
    * @Description: ElasticSearch简单模式-复杂查询
    * @Author: Mr.Zhang
    * @Version: 1.0
    * @Date:  2022/7/24 19:11
    * @Parameters: []
    * @Return void
    ======================================================================================*/
    @Test
    public void testComplexQuery() throws Exception {

        // 获取连接对象
        TransportClient client = ESClientUtil.getClient();

        // 得到搜索的对象
        SearchRequestBuilder builder = client.prepareSearch("pethome").setTypes("user");

        // 设置query里面的查询条件
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.matchQuery("name","我在源码"));
        boolQueryBuilder.filter(QueryBuilders.termQuery("sex",1))
                        .filter(QueryBuilders.rangeQuery("age").gte(1).lte(12));

        // 把搜索的条件放进去
        builder.setQuery(boolQueryBuilder);
        builder.setFrom(2);
        builder.setSize(3);
        builder.addSort("age",SortOrder.DESC);

        // 拿到搜索的结果
        SearchHit[] hits = builder.get().getHits().getHits();

        // 打印
        System.out.println(hits);
        // 打印每一条数据
        for (SearchHit document : hits) {
            System.out.println(document.getSourceAsMap());
        }

        // 关流
        client.close();
    }




   /**======================================================================================
   * @Title: testComplex
   * @Description: 复制查询所需要的数据,批量新增工具类
   * @Author: Mr.Zhang
   * @Version: 1.0
   * @Date:  2022/7/24 18:49
   * @Parameters: []
   * @Return void
   ======================================================================================*/
   @Test
   public void testBatch() throws Exception {
       // 1.获取ES连接
       TransportClient client = ESClientUtil.getClient();
       // 2.创建批量操作对象
       BulkRequestBuilder bulk = client.prepareBulk();
       // 3.批量创建文档，放入批量操作对象中
       for (int i = 2; i < 100; i++) {
           IndexRequestBuilder builder = client.prepareIndex("pethome", "user", i + "").setSource(
                   XContentFactory.jsonBuilder()
                           .startObject()
                           .field("id", i - 1)
                           .field("name", "我在源码学习Java!" + i)
                           .field("age", i - 1)
                           .field("sex", i%2)
                           .endObject()
           );
           BulkResponse result = bulk.add(builder).get();
           System.out.println(result.status());
       }
       // 4.关闭连接
       client.close();
   }
}
